import React, {Component} from 'react';

//1. 创建Context对象
const DataContext = React.createContext()

class Context extends Component {
    state = {username: 'Teacher'}

    render() {
        return (
            <div>
                <h3> I am Context Component</h3>
                <h4> My userName: {this.state.username}</h4>
                {/*2.包裹对象*/}
                <DataContext.Provider value={this.state.username}>
                    <One/>
                </DataContext.Provider>
            </div>
        );
    }
}

class One extends Component {
    render() {
        return (
            <>
                <h3> I am One Component</h3>
                <Two/>
            </>
        );
    }
}

class Two extends Component {
    // 3.声明接收(类式组件)
    static contextType = DataContext

    render() {
        return (
            <>
                <h3> I am Two Component</h3>
                <h4> Form One userName: {this.context}</h4>
                <Thread/>
            </>
        );
    }
}

function Thread() {
    return (
        <>
            <h3> I am Thread Component</h3>
            {/*函数式组件使用方式*/}
            <DataContext.Consumer>
                {
                    value => {
                        return <h4> Form One userName: {value}</h4>
                    }
                }
            </DataContext.Consumer>
        </>
    );
}

export default Context;